package shujia.day18.tcpdemo3;

import shujia.day18.DateUtil;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

public class ClientThread extends Thread{

    private Socket s;

    public ClientThread(Socket socket) {
        this.s = socket;
    }

    @Override
    public void run() {
        //在服务器端获取客户端的信息
        InetAddress inetAddress = s.getInetAddress();
        String hostName = inetAddress.getHostName();
        String ip = inetAddress.getHostAddress();
        System.out.println("用户: "+hostName+"已上线！！");
        try {
            //获取通道中的输入流对象，获取客户端发送的数据
            InputStream inputStream = s.getInputStream();
            //获取通道中的输出流对象，给客户端写反馈
            OutputStream outputStream = s.getOutputStream();


            while (true){

                byte[] bytes = new byte[1024];
                int length = inputStream.read(bytes);
                String time = DateUtil.getTime(System.currentTimeMillis());

                String info = new String(bytes, 0, length);
                System.out.println(time);
                System.out.println(hostName+": "+info);
                System.out.println();

                outputStream.write("服务器已收到！".getBytes());
                outputStream.flush();

            }
        }catch (Exception e){
            System.out.println("------------------------------");
            System.out.println("用户: "+hostName+"已下线.....");
            System.out.println("------------------------------");
        }
    }
}
